package org.nmgyjt.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jose.JOSEException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.*;
import org.nmgyjt.springboot.entity.ApiRes;
import org.nmgyjt.springboot.entity.admin.*;
import org.nmgyjt.springboot.entity.organization.Organization;
import org.nmgyjt.springboot.entity.protectTarget.ProtectTargetInfo;
import org.nmgyjt.springboot.entity.refuge.RefugeInfo;
import org.nmgyjt.springboot.entity.rescueTeam.RescueTeam;
import org.nmgyjt.springboot.entity.storeInfo.StoreInfo;
import org.nmgyjt.springboot.service.*;
import org.nmgyjt.springboot.utils.HttpUtils;
import org.nmgyjt.springboot.utils.IDAASUserUtils;
import org.nmgyjt.springboot.utils.NMGYJTIDAASTokenUtils;
import org.nmgyjt.springboot.utils.ZWWXUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IdaasServiceImpl implements IdaasService {
    @Autowired
    OrganizationService organizationService;
    @Autowired
    ICsSystemAdminService adminService;
    @Autowired
    ICsSystemAdminMenuRelService menuRelService;
    @Autowired
    ICsSystemDeptService deptService;

    @Autowired
    IIdaasAreaService idaasAreaService;

    @Autowired
    CsSystemDeptServiceImpl deptServiceImpl;
    @Autowired
    ICsSystemSourceExtService csSystemSourceExtService;

    @Autowired
    RescueTeamService rescueTeamService;
    @Autowired
    StoreService storeService;

    @Autowired
    ProtectTargetService protectTargetService;

    @Autowired
    RefugeService refugeService;

    @Autowired
    ICsSystemSourceTypeService iCsSystemSourceTypeService;

    @Autowired
    ZWWXUtils zwwxUtils;

    @Async
    public void saveBaseSource(CsSystemSourceExt sourceExt, CsSystemOrgCreateBean dept) {
        try {
            log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<四类资源管理员id{}", dept.getUserId());
            if ("1000000010".equals(sourceExt.getMenuId())) {
                RescueTeam rescueTeam = new RescueTeam();
                rescueTeam.setDepId(sourceExt.getOrgId());
                rescueTeam.setTeamName(dept.getOrgName());
                rescueTeam.setSuperDepartment(sourceExt.getSuperiorOrgName());
                rescueTeam.setSuperDepartmentId(sourceExt.getSuperiorOrgId());
                //20240307李处要求主要救援去掉
//                JSONArray jsonArrayMajorDuties = JSON.parseArray(sourceExt.getMajorDuties());
//                String strMajorDuties="";
                String strSecondaryDuties="";
//                for(Object object:jsonArrayMajorDuties){
//                    strMajorDuties=strMajorDuties+object.toString()+",";
//                }
//                rescueTeam.setMajorDuties(strMajorDuties.substring(0,strMajorDuties.length()-1));
                JSONArray jsonArraySecondaryDuties = JSON.parseArray(sourceExt.getSecondaryDuties());
                for(Object object:jsonArraySecondaryDuties){
                    strSecondaryDuties=strSecondaryDuties+object.toString()+",";
                }
                rescueTeam.setSecondaryDuties(strSecondaryDuties.substring(0,strSecondaryDuties.length()-1));
                JSONArray jsonArray = JSON.parseArray(sourceExt.getSourceType());
                log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*********>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>获取类型数组：{}", jsonArray);

                if (jsonArray.size() > 0) {
                    String sourceType = jsonArray.getString(jsonArray.size() - 1);
                    CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                    rescueTeam.setTeamType(csSystemSourceType.getName());
                    rescueTeam.setTeamTypeCode(csSystemSourceType.getId());
                    rescueTeam.setFirstTeamType(csSystemSourceType.getId());
//                    if (StringUtils.isEmpty(sourceType)) {
//                        sourceType = jsonArray.getString(jsonArray.size() - 1);
//                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
//                        rescueTeam.setTeamType(csSystemSourceType.getName());
//                        rescueTeam.setTeamTypeCode(csSystemSourceType.getId());
//                        rescueTeam.setFirstTeamType(csSystemSourceType.getId());
//                    } else {
//                        String firstSourceType = jsonArray.getString(jsonArray.size() - 1);
//                        CsSystemSourceType csSystemSourceTypeFirst = iCsSystemSourceTypeService.getById(firstSourceType);
//                        rescueTeam.setFirstTeamType(csSystemSourceTypeFirst.getId());
//                        String[] sourceTypeIds=sourceType.split(":");
//                        QueryWrapper<CsSystemSourceType> queryWrapper=new QueryWrapper<>();
//                        queryWrapper.in("id",sourceTypeIds);
//                        List<CsSystemSourceType> csSystemSourceTypes = iCsSystemSourceTypeService.list(queryWrapper);
//                        log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*********>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>获取类型对象：{}", csSystemSourceTypes.toString());
//                        String ids="";
//                        String names="";
//                        for(CsSystemSourceType csSystemSourceType:csSystemSourceTypes){
//                            ids=ids+csSystemSourceType.getId()+",";
//                            names=names+csSystemSourceType.getName()+",";
//                        }
//                        rescueTeam.setTeamType(csSystemSourceTypeFirst.getName()+"："+names.substring(0, names.length() - 1));
//                        rescueTeam.setTeamTypeCode(ids.substring(0, ids.length() - 1));
//                    }

                }
                String leveled = "";
                String snycLevel = "";
                ObjectMapper objectMapper = new ObjectMapper();
                log.info("*********获取级别：{}", sourceExt.getSourceLevel());
                CsSystemSourceLevelBean csSystemSourceLevelBean = objectMapper.readValue(sourceExt.getSourceLevel(), CsSystemSourceLevelBean.class);
                log.info("*********获取级别对象：{}", csSystemSourceLevelBean.toString());
                if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
                        !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCountry())) {
                    leveled = leveled + "国家级,";
                    snycLevel = snycLevel + "1,";
                }
                if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
                        !ObjectUtils.isEmpty(csSystemSourceLevelBean.getProvince())) {
                    leveled = leveled + "自治区级,";
                    snycLevel = snycLevel + "2,";
                }
                if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
                        !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCity())) {
                    QueryWrapper<IdaasArea> idaasAreaQueryWrapper = new QueryWrapper<>();
                    IdaasArea area = idaasAreaService.getById(csSystemSourceLevelBean.getCity());
                    leveled = leveled + area.getName() + ",";
                    snycLevel = snycLevel + "3,";
                    rescueTeam.setLevelCityRegionCode(area.getId().substring(0, 6));
                    rescueTeam.setLevelCityRegionName(area.getName());
                }
                if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
                        !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCounty())) {
                    IdaasArea area = idaasAreaService.getById(csSystemSourceLevelBean.getCounty());
                    leveled = leveled + area.getName() + ",";
                    snycLevel = snycLevel + "4,";
                    rescueTeam.setLevelCountryRegionCode(area.getId().substring(0, 6));
                    rescueTeam.setLevelCountryRegionName(area.getName());
                }
                if (!"".equals(leveled)) {
                    leveled = leveled.substring(0, leveled.length() - 1);
                    snycLevel = snycLevel.substring(0, snycLevel.length() - 1);
                }
                rescueTeam.setLeveled(leveled);
                rescueTeam.setSyncLevel(snycLevel);
                rescueTeam.setAreaCode(dept.getAreaCode().substring(0, 6));
                log.info("》》》》》》》》》》》》》》》》》》》》areaCode：{}", dept.getAreaCode().substring(0, 6));
                rescueTeam.setState("2");
                rescueTeamService.save(rescueTeam);

//                String ssoAccessToken=zwwxUtils.getGovWxToken();
//                zwwxUtils.getZWUserInfo(rescueTeam.getHeadPhone(),"rescue/rescue-detail?depId="+rescueTeam.getDepId(),ssoAccessToken);
            }
            if ("1000000011".equals(sourceExt.getMenuId())) {
                log.info("*********仓库添加：{}", dept.getOrgName());
                StoreInfo storeInfo = new StoreInfo();
                storeInfo.setDepId(sourceExt.getOrgId());
                storeInfo.setStoreName(dept.getOrgName());
                storeInfo.setSuperDepartment(sourceExt.getSuperiorOrgName());
                storeInfo.setSuperDepartmentId(sourceExt.getSuperiorOrgId());
                storeInfo.setAreaCode(dept.getAreaCode().substring(0, 6));
                storeInfo.setState("2");
                boolean b = storeService.save(storeInfo);

//                String ssoAccessToken=zwwxUtils.getGovWxToken();
//                zwwxUtils.getZWUserInfo(storeInfo.getHeadPhone(),"supplies/supplies-detail?depId="+storeInfo.getDepId(),ssoAccessToken);
                log.info("*********仓库添加：{}", b);
            }
            if ("1000000012".equals(sourceExt.getMenuId())) {
                log.info("*********防护添加：{}", dept.getOrgName());
                ProtectTargetInfo protectTargetInfo = new ProtectTargetInfo();
                protectTargetInfo.setDepId(sourceExt.getOrgId());
                protectTargetInfo.setProtectName(dept.getOrgName());
                JSONArray jsonArray = JSON.parseArray(sourceExt.getSourceType());
                if (jsonArray.size() > 0) {
                    String sourceType = jsonArray.getString(jsonArray.size() - 1);
                    if (StringUtils.isEmpty(sourceType)) {
                        sourceType = jsonArray.getString(jsonArray.size() - 2);
                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                        protectTargetInfo.setProtectType(csSystemSourceType.getName());
                        protectTargetInfo.setProtectTypeCode(csSystemSourceType.getId());
                        protectTargetInfo.setSecondType(csSystemSourceType.getName());
                        protectTargetInfo.setSecondTypeCode(csSystemSourceType.getId());
                    } else {
                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                        log.info("*********获取类型对象：{}", csSystemSourceType.toString());
                        protectTargetInfo.setProtectType(csSystemSourceType.getName());
                        protectTargetInfo.setProtectTypeCode(csSystemSourceType.getId());
                        String secondTypeCode = csSystemSourceType.getId().
                                substring(0, csSystemSourceType.getId().length() - 2) + "00";
                        CsSystemSourceType secondType = iCsSystemSourceTypeService.getById(secondTypeCode);
                        protectTargetInfo.setSecondType(secondType.getName());
                        protectTargetInfo.setSecondTypeCode(secondTypeCode);
                    }

                }
                protectTargetInfo.setSuperDepartment(sourceExt.getSuperiorOrgName());
                protectTargetInfo.setSuperDepartmentId(sourceExt.getSuperiorOrgId());
                protectTargetInfo.setAreaCode(dept.getAreaCode().substring(0, 6));
                protectTargetInfo.setState("2");
                boolean b = protectTargetService.save(protectTargetInfo);

//                String ssoAccessToken=zwwxUtils.getGovWxToken();
//                zwwxUtils.getZWUserInfo(protectTargetInfo.getFirstHeadPhone(),"protect-unit-detail/index?depId="+protectTargetInfo.getDepId(),ssoAccessToken);
                log.info("*********防护添加：{}", b);
            }
            if ("1000000014".equals(sourceExt.getMenuId())) {
                log.info("*********避难添加：{}", dept.getOrgName());
                RefugeInfo refugeInfo = new RefugeInfo();
                refugeInfo.setDepId(sourceExt.getOrgId());
                refugeInfo.setRefugeName(dept.getOrgName());
                JSONArray jsonArray = JSON.parseArray(sourceExt.getSourceType());
                log.info("*********获取类型数组：{}", jsonArray);
                if (jsonArray.size() > 0) {
                    String sourceType = jsonArray.getString(jsonArray.size() - 1);
                    if (StringUtils.isEmpty(sourceType)) {
                        sourceType = jsonArray.getString(jsonArray.size() - 2);
                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                        refugeInfo.setRefugeType(csSystemSourceType.getName());
                        refugeInfo.setRefugeTypeCode(csSystemSourceType.getId());
                    } else {
                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                        log.info("*********获取类型对象：{}", csSystemSourceType.toString());
                        refugeInfo.setRefugeType(csSystemSourceType.getName());
                        refugeInfo.setRefugeTypeCode(csSystemSourceType.getId());
                    }

                }
                refugeInfo.setSuperDepartment(sourceExt.getSuperiorOrgName());
                refugeInfo.setSuperDepartmentId(sourceExt.getSuperiorOrgId());
                refugeInfo.setAreaCode(dept.getAreaCode().substring(0, 6));
                refugeInfo.setState("2");
                boolean b = refugeService.save(refugeInfo);

//                String ssoAccessToken=zwwxUtils.getGovWxToken();
//                zwwxUtils.getZWUserInfo(refugeInfo.getHeadPhone(),"refuge-detail/index?depId="+refugeInfo.getDepId(),ssoAccessToken);
                log.info("*********避难添加：{}", b);
            }
        } catch (Exception e) {
            e.printStackTrace();
//            throw new RuntimeException(e);
        }
    }

    @Override
    public void exist(String phone) {
//        try {
//            HashMap<String, String> headerParams = new HashMap<>();
//            headerParams.put("Content-Type", "application/json");
//            headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());
//            Map<String, String> bodyParam2 = new HashMap();
//            bodyParam2.put("object_type", "DEPT");
//            String clientPostRes = HttpUtils.httpGet(
//                    "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + userInfo.getValues().getDeptId() + "/traces",
//                    bodyParam2, headerParams);
//            List<IDAASDeptResponse> listResponse = JSONArray.parseArray(clientPostRes, IDAASDeptResponse.class);
//            String orgName = "";
//            if (null != listResponse && listResponse.size() > 2) {
//
//                orgName = listResponse.get(listResponse.size() - 1).getValues().getName() +
//                        "--" + listResponse.get(listResponse.size() - 2).getValues().getName() +
//                        "--" + listResponse.get(listResponse.size() - 3).getValues().getName();
//
//            } else if (null != listResponse && listResponse.size() > 1) {
//                orgName = listResponse.get(listResponse.size() - 1).getValues().getName() +
//                        "--" + listResponse.get(listResponse.size() - 2).getValues().getName();
//            } else if (null != listResponse && listResponse.size() > 0) {
//                orgName = listResponse.get(listResponse.size() - 1).getValues().getName();
//            }
//            List<CsSystemAdmin> systemAdmins = adminServiceImpl.list(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getOrgId, userInfo.getValues().getDeptId()));
//            Map<String, String> info = new HashMap<>();
//            info.put("orgName", "\"" + orgName + "\"");
//            if (null != systemAdmins && !CollectionUtils.isEmpty(systemAdmins)) {
//                info.put("name", systemAdmins.get(0).getName());
//                info.put("phone", systemAdmins.get(0).getPhone());
//            } else {
//                info.put("name", "");
//                info.put("phone", "");
//            }
//        } catch (ParseException e) {
//            throw new RuntimeException(e);
//        } catch (JOSEException e) {
//            throw new RuntimeException(e);
//        }
    }

    @Async
    public void updateBaseSource(CsSystemSourceExt sourceExt, CsSystemAdminCreateBean bean) {
        try {
            if ("1000000010".equals(sourceExt.getMenuId())) {
                QueryWrapper<RescueTeam> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("dep_id", sourceExt.getOrgId());
                RescueTeam rescueTeam = rescueTeamService.getOne(queryWrapper);
                if (ObjectUtils.isEmpty(rescueTeam)) {
                    rescueTeam = new RescueTeam();
                    rescueTeam.setDepId(sourceExt.getOrgId());
                    rescueTeam.setSuperDepartment(sourceExt.getSuperiorOrgName());
                    rescueTeam.setSuperDepartmentId(sourceExt.getSuperiorOrgId());
                    if (bean.getAreaCode() !=null ){
                        rescueTeam.setAreaCode(bean.getAreaCode().substring(0, 6));
                    }
                    rescueTeam.setState("2");
                    log.info("*********队伍新增");
                } else {
                    log.info("*********队伍修改");
                }
                rescueTeam.setTeamName(bean.getOrgName());
                //20240307李处要求主要救援去掉
//                JSONArray jsonArrayMajorDuties = JSON.parseArray(sourceExt.getMajorDuties());
//                String strMajorDuties="";
                String strSecondaryDuties="";
//                for(Object object:jsonArrayMajorDuties){
//                    strMajorDuties=strMajorDuties+object.toString()+",";
//                }
//                rescueTeam.setMajorDuties(strMajorDuties.substring(0,strMajorDuties.length()-1));
                JSONArray jsonArraySecondaryDuties = JSON.parseArray(sourceExt.getSecondaryDuties());
                for(Object object:jsonArraySecondaryDuties){
                    strSecondaryDuties=strSecondaryDuties+object.toString()+",";
                }
                rescueTeam.setSecondaryDuties(strSecondaryDuties.substring(0,strSecondaryDuties.length()-1));
                JSONArray jsonArray = JSON.parseArray(sourceExt.getSourceType());
                log.info("*********获取类型数组：{}", jsonArray);
                if (null != sourceExt && null != sourceExt.getSourceType() && !CollectionUtils.isEmpty(jsonArray)) {
                    String sourceType = jsonArray.getString(jsonArray.size() - 1);
                    CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                    rescueTeam.setTeamType(csSystemSourceType.getName());
                    rescueTeam.setTeamTypeCode(csSystemSourceType.getId());
                    rescueTeam.setFirstTeamType(csSystemSourceType.getId());
//                    if (StringUtils.isEmpty(sourceType)) {
//                        sourceType = jsonArray.getString(jsonArray.size() - 2);
//                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
//                        rescueTeam.setTeamType(csSystemSourceType.getName());
//                        rescueTeam.setTeamTypeCode(csSystemSourceType.getId());
//                        rescueTeam.setFirstTeamType(csSystemSourceType.getId());
//                    } else {
//                        String firstSourceType = jsonArray.getString(jsonArray.size() - 2);
//                        CsSystemSourceType csSystemSourceTypeFirst = iCsSystemSourceTypeService.getById(firstSourceType);
//                        rescueTeam.setFirstTeamType(csSystemSourceTypeFirst.getId());
//                        String[] sourceTypeIds=sourceType.split(":");
//                        QueryWrapper<CsSystemSourceType> queryWrapperc=new QueryWrapper<>();
//                        queryWrapperc.in("id",sourceTypeIds);
//                        List<CsSystemSourceType> csSystemSourceTypes = iCsSystemSourceTypeService.list(queryWrapperc);
//                        log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*********>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>获取类型对象：{}", csSystemSourceTypes.toString());
//                        String ids="";
//                        String names="";
//                        for(CsSystemSourceType csSystemSourceType:csSystemSourceTypes){
//                            ids=ids+csSystemSourceType.getId()+",";
//                            names=names+csSystemSourceType.getName()+",";
//                        }
//                        rescueTeam.setTeamType(csSystemSourceTypeFirst.getName()+"："+names.substring(0, names.length() - 1));
//                        rescueTeam.setTeamTypeCode(ids.substring(0, ids.length() - 1));
//                    }

                }
                String leveled = "";
                String snycLevel = "";
                ObjectMapper objectMapper = new ObjectMapper();
                log.info("*********获取级别：{}", sourceExt.getSourceLevel());
                CsSystemSourceLevelBean csSystemSourceLevelBean = objectMapper.readValue(sourceExt.getSourceLevel(), CsSystemSourceLevelBean.class);
                log.info("*********获取级别对象：{}", csSystemSourceLevelBean.toString());
                if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
                        !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCountry())) {
                    leveled = leveled + "国家级,";
                    snycLevel = snycLevel + "1,";
                }
                if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
                        !ObjectUtils.isEmpty(csSystemSourceLevelBean.getProvince())) {
                    leveled = leveled + "自治区级,";
                    snycLevel = snycLevel + "2,";
                }
                if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
                        !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCity())) {
                    QueryWrapper<IdaasArea> idaasAreaQueryWrapper = new QueryWrapper<>();
                    IdaasArea area = idaasAreaService.getById(csSystemSourceLevelBean.getCity());
                    leveled = leveled + area.getName() + ",";
                    snycLevel = snycLevel + "3,";
                    rescueTeam.setLevelCityRegionCode(area.getId().substring(0, 6));
                    rescueTeam.setLevelCityRegionName(area.getName());
                }
                if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
                        !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCounty())) {
                    IdaasArea area = idaasAreaService.getById(csSystemSourceLevelBean.getCounty());
                    leveled = leveled + area.getName() + ",";
                    snycLevel = snycLevel + "4,";
                    rescueTeam.setLevelCountryRegionCode(area.getId().substring(0, 6));
                    rescueTeam.setLevelCountryRegionName(area.getName());
                }
                if (!"".equals(leveled)) {
                    leveled = leveled.substring(0, leveled.length() - 1);
                    snycLevel = snycLevel.substring(0, snycLevel.length() - 1);
                }
                rescueTeam.setLeveled(leveled);
                rescueTeam.setSyncLevel(snycLevel);
                rescueTeamService.saveOrUpdate(rescueTeam);
            }
            if ("1000000011".equals(sourceExt.getMenuId())) {
                log.info("*********修改仓库：{}", bean.getOrgName());
                QueryWrapper<StoreInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("dep_id", sourceExt.getOrgId());
                StoreInfo storeInfo = storeService.getOne(queryWrapper);
                if (ObjectUtils.isEmpty(storeInfo)) {
                    storeInfo = new StoreInfo();
                    storeInfo.setDepId(sourceExt.getOrgId());
                    storeInfo.setSuperDepartment(sourceExt.getSuperiorOrgName());
                    storeInfo.setSuperDepartmentId(sourceExt.getSuperiorOrgId());
                    if (bean.getAreaCode() !=null ){
                        storeInfo.setAreaCode(bean.getAreaCode().substring(0, 6));
                    }
                    storeInfo.setState("2");
                    log.info("*********仓库新增");
                } else {
                    log.info("*********仓库修改");
                }
                storeInfo.setStoreName(bean.getOrgName());
                boolean b = storeService.saveOrUpdate(storeInfo);
                log.info("*********仓库添加：{}", b);
            }
            if ("1000000012".equals(sourceExt.getMenuId())) {
                QueryWrapper<ProtectTargetInfo> protectTargetInfoQueryWrapper = new QueryWrapper<>();
                protectTargetInfoQueryWrapper.eq("dep_id", sourceExt.getOrgId());
                ProtectTargetInfo protectTargetInfo = protectTargetService.getOne(protectTargetInfoQueryWrapper);
                if (ObjectUtils.isEmpty(protectTargetInfo)) {
                    protectTargetInfo = new ProtectTargetInfo();
                    protectTargetInfo.setDepId(sourceExt.getOrgId());
                    protectTargetInfo.setSuperDepartment(sourceExt.getSuperiorOrgName());
                    protectTargetInfo.setSuperDepartmentId(sourceExt.getSuperiorOrgId());
                    if (bean.getAreaCode() !=null ){
                        protectTargetInfo.setAreaCode(bean.getAreaCode().substring(0, 6));
                    }
                    protectTargetInfo.setState("2");
                    log.info("*********防护新增");
                } else {
                    log.info("*********防护修改");
                }
                protectTargetInfo.setProtectName(bean.getOrgName());
                JSONArray jsonArray = JSON.parseArray(sourceExt.getSourceType());
                if (jsonArray.size() > 0) {
                    String sourceType = jsonArray.getString(jsonArray.size() - 1);
                    if (StringUtils.isEmpty(sourceType)) {
                        sourceType = jsonArray.getString(jsonArray.size() - 2);
                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                        protectTargetInfo.setProtectType(csSystemSourceType.getName());
                        protectTargetInfo.setProtectTypeCode(csSystemSourceType.getId());
                        protectTargetInfo.setSecondType(csSystemSourceType.getName());
                        protectTargetInfo.setSecondTypeCode(csSystemSourceType.getId());
                    } else {
                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                        log.info("*********获取类型对象：{}", csSystemSourceType.toString());
                        protectTargetInfo.setProtectType(csSystemSourceType.getName());
                        protectTargetInfo.setProtectTypeCode(csSystemSourceType.getId());
                        String secondTypeCode = csSystemSourceType.getId().
                                substring(0, csSystemSourceType.getId().length() - 2) + "00";
                        CsSystemSourceType secondType = iCsSystemSourceTypeService.getById(secondTypeCode);
                        protectTargetInfo.setSecondType(secondType.getName());
                        protectTargetInfo.setSecondTypeCode(secondTypeCode);
                    }

                }
                boolean b = protectTargetService.saveOrUpdate(protectTargetInfo);
            }
            if ("1000000014".equals(sourceExt.getMenuId())) {
                log.info("*********避难修改：{}", bean.getOrgName());
                QueryWrapper<RefugeInfo> refugeInfoQueryWrapper = new QueryWrapper<>();
                refugeInfoQueryWrapper.eq("dep_id", sourceExt.getOrgId());
                RefugeInfo refugeInfo = refugeService.getOne(refugeInfoQueryWrapper);
                if (ObjectUtils.isEmpty(refugeInfo)) {
                    refugeInfo = new RefugeInfo();
                    refugeInfo.setDepId(sourceExt.getOrgId());
                    refugeInfo.setSuperDepartment(sourceExt.getSuperiorOrgName());
                    refugeInfo.setSuperDepartmentId(sourceExt.getSuperiorOrgId());
                    if (bean.getAreaCode() !=null ){
                        refugeInfo.setAreaCode(bean.getAreaCode().substring(0, 6));
                    }
                    refugeInfo.setState("2");
                    log.info("*********避难新增");
                } else {
                    log.info("*********避难修改");
                }
                refugeInfo.setRefugeName(bean.getOrgName());
                JSONArray jsonArray = JSON.parseArray(sourceExt.getSourceType());
                log.info("*********获取类型数组：{}", jsonArray);
                if (null != sourceExt && null != sourceExt.getSourceType() && !CollectionUtils.isEmpty(jsonArray)) {
                    String sourceType = jsonArray.getString(jsonArray.size() - 1);
                    if (StringUtils.isEmpty(sourceType)) {
                        sourceType = jsonArray.getString(jsonArray.size() - 2);
                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                        refugeInfo.setRefugeType(csSystemSourceType.getName());
                        refugeInfo.setRefugeTypeCode(csSystemSourceType.getId());
                    } else {
                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(sourceType);
                        log.info("*********获取类型对象：{}", csSystemSourceType.toString());
                        refugeInfo.setRefugeType(csSystemSourceType.getName());
                        refugeInfo.setRefugeTypeCode(csSystemSourceType.getId());
                    }

                }
                boolean b = refugeService.saveOrUpdate(refugeInfo);
                log.info("*********避难添加：{}", b);
            }
        } catch (Exception e) {
            e.printStackTrace();
//            throw new RuntimeException(e);
        }
    }

    @Override
    public Map selectCsSystemUser(CsSystemUserstatisticBean bean) throws ParseException, JOSEException {
        //UserInfo loginAdminInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getCreatedBy());
        CsSystemAdmin admin = adminService.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, bean.getCreatedBy()).orderByDesc(CsSystemAdmin::getId).last("limit 1"));

        CsSystemAdminMenuRel menuRel = menuRelService.getById(bean.getMenuID());
        bean.setMenuName(menuRel.getName());

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        String orgId = null;
        List<String> orgIdList = new ArrayList<>();
        Map<String, String> bodyParam = new HashMap();
        bodyParam.put("object_type", "DEPT");
        if ("党委管理员".equals(bean.getMenuName()) || "政府管理员".equals(bean.getMenuName())) {
            bean.setOrgName("管理员");
            String filterOrgName = "党委管理员".equals(bean.getMenuName()) ? "党委领导" : "政府领导";
            String org = admin.getOrgId();
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + org + "/traces";
            String str1 = HttpUtils.httpGet(url1, bodyParam, headerParams);
            IDAASDeptResponse interDeptResponse = deptServiceImpl.getOrgInfoFromIDAASOrgList(str1, filterOrgName);
            if (null != interDeptResponse && StringUtils.isNotEmpty(interDeptResponse.getId())) {
                orgIdList.add(interDeptResponse.getId());
            }

        } else if ("领导班子".equals(bean.getMenuName())) {
            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId() + "/children";
            String str2 = HttpUtils.httpGet(url2, bodyParam, headerParams);
            IDAASDeptResponse deptResponse = deptServiceImpl.getOrgInfoFromIDAASOrgList(str2, "领导班子");
            orgId = deptResponse.getId();
            orgIdList.add(orgId);
        } else if ("内设机构".equals(bean.getMenuName())) {
            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId() + "/traces";
            String str2 = HttpUtils.httpGet(url2, bodyParam, headerParams);
            IDAASDeptResponse info = deptServiceImpl.getOrgInfoFromIDAASOrgList(str2, "内设机构");
            String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + info.getId() + "/children";
            String str3 = HttpUtils.httpGet(url3, bodyParam, headerParams);
            List<IDAASDeptResponse> deptResponses = JSONArray.parseArray(str3, IDAASDeptResponse.class);
            for (IDAASDeptResponse deptResponse : deptResponses) {
                orgIdList.add(deptResponse.getId());
            }
            orgId = info.getId();
        } else {
            orgId = admin.getOrgId();
            orgIdList.add(orgId);
        }


        //{"objectType":"USER","values":{"status":[],"deptId":["dp-13a3d93558a3444880c199487ab62fba"],"identityClassification":"defaultIdentityClassification"}}
        // {"objectType":"USER","values":{"deptId":["dp-13a3d93558a3444880c199487ab62fba"],"identityClassification":"defaultIdentityClassification","status":[]}}


        Map bodyParam2 = new HashMap();
        bodyParam2.put("status", new ArrayList<>());

        bodyParam2.put("deptId", orgIdList);
        bodyParam2.put("identityClassification", "defaultIdentityClassification");
        Map bodyParams = new HashMap();
        bodyParams.put("objectType", "USER");
        bodyParams.put("values", bodyParam2);

        String url2 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + orgId + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
        String str1 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(bodyParams), headerParams);
        IDAASUserResponse object = JSONObject.parseObject(str1, IDAASUserResponse.class);
        List<CsSystemUserCreateBean> users = new ArrayList<>();
        List<CsSystemUserCreateBean> retUsers = new ArrayList<>();
        if (null != object && !CollectionUtils.isEmpty(object.getData())) {
            int i = 1;
            for (UserInfo user : object.getData()) {
                if (!user.getValues().getUsername().equals(bean.getCreatedBy())) {
                    if (bean.getIsLeader() == user.getValues().getIsLeader()) {
                        CsSystemUserCreateBean userBean = new CsSystemUserCreateBean();
                        userBean.setIsLeader(user.getValues().getIsLeader());
                        userBean.setJob(user.getValues().getJobPosition());
                        userBean.setName(user.getValues().getDisplayName());
                        userBean.setPhone(user.getValues().getUsername());
                        userBean.setOrgName(user.getValues().getOfficeAddress());
                        userBean.setUdOrder(user.getValues().getUdOrder());
                        userBean.setWorkUnit(user.getValues().getWorkUnit());
                        userBean.setOfficeAddress(user.getValues().getOfficeAddress());
                        userBean.setId(user.getId());
                        if (null == userBean.getUdOrder()) {
                            userBean.setUdOrder(i);
                        } else {
                            i = userBean.getUdOrder();
                        }

                        if ("1000000013".equals(bean.getMenuID())) {
                            CsSystemSourceExt sourceExt = csSystemSourceExtService.getOne(new LambdaQueryWrapper<CsSystemSourceExt>().eq(CsSystemSourceExt::getMenuId, bean.getMenuID()).eq(CsSystemSourceExt::getOrgId, user.getId()));
                            if (null != sourceExt) {
                                userBean.setSourceType(sourceExt.getSourceType());
                                userBean.setDesc(sourceExt.getRemark());
                                userBean.setJobLevel(user.getValues().getJobLevel());
                                userBean.setJobType(user.getValues().getJobType());
                                users.add(userBean);
                            }
                            if (StringUtils.isNotEmpty(bean.getType())) {
                                CsSystemSourceExt sourceExtByType = csSystemSourceExtService.getOne(new LambdaQueryWrapper<CsSystemSourceExt>().eq(CsSystemSourceExt::getMenuId, bean.getMenuID()).eq(CsSystemSourceExt::getOrgId, user.getId()).eq(CsSystemSourceExt::getSourceType, bean.getType()));
                                if (null != sourceExtByType && StringUtils.isNotEmpty(bean.getName()) && user.getValues().getDisplayName().equals(bean.getName())) {
                                    userBean.setSourceType(sourceExtByType.getSourceType());
                                    userBean.setDesc(sourceExtByType.getRemark());
                                    userBean.setJobLevel(user.getValues().getJobLevel());
                                    userBean.setJobType(user.getValues().getJobType());
                                    retUsers.add(userBean);
                                }
                                if (null != sourceExtByType && StringUtils.isEmpty(bean.getName())) {
                                    userBean.setSourceType(sourceExtByType.getSourceType());
                                    userBean.setDesc(sourceExtByType.getRemark());
                                    userBean.setJobLevel(user.getValues().getJobLevel());
                                    userBean.setJobType(user.getValues().getJobType());
                                    retUsers.add(userBean);
                                }
                            } else {
                                if (null != sourceExt) {
                                    if (StringUtils.isNotEmpty(bean.getName()) && user.getValues().getDisplayName().equals(bean.getName())) {
                                        userBean.setSourceType(sourceExt.getSourceType());
                                        userBean.setDesc(sourceExt.getRemark());
                                        userBean.setJobLevel(user.getValues().getJobLevel());
                                        userBean.setJobType(user.getValues().getJobType());
                                        retUsers.add(userBean);
                                    }
                                    if (StringUtils.isEmpty(bean.getName())) {
                                        userBean.setSourceType(sourceExt.getSourceType());
                                        userBean.setDesc(sourceExt.getRemark());
                                        userBean.setJobLevel(user.getValues().getJobLevel());
                                        userBean.setJobType(user.getValues().getJobType());
                                        retUsers.add(userBean);
                                    }
                                }
                            }
                        }

                        i = i + 1;
                    }
                }
            }
        }
        Map<String, List<CsSystemUserCreateBean>> groupBusinessCollection = users.stream().collect(Collectors.groupingBy(CsSystemUserCreateBean::getSourceType));
        Integer expErtNum = users.size();
        Integer expErtTypeNum = groupBusinessCollection.size();
        Map map = new LinkedHashMap();
        map.put("expErtNum", expErtNum);
        map.put("expErtTypeNum", expErtTypeNum);
        map.put("list", users);
        return map;
    }

    @Override
    public JSONObject syncDepartment() {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        try {
            headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
            int pageIndex = 0;
            int pageSize = 500;
            for (; ; ) {
                Map<String, String> map = new HashMap();
                map.put("page_index", String.valueOf(pageIndex));
                map.put("page_size", String.valueOf(pageSize));
                String clientPostRes = HttpUtils.httpGet(
                        "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments", map, headerParams);
                JSONObject jsonObject = JSON.parseObject(clientPostRes);
                JSONArray depArray = jsonObject.getJSONArray("data");
                if (depArray.size() < 1) {
                    break;
                }
                List<Organization> organizationList = new ArrayList<>();
                for (int i = 0; i < depArray.size(); i++) {
                    Organization organization = new Organization();
                    organization.setId(depArray.getJSONObject(i).getString("id"));
                    organization.setCode(depArray.getJSONObject(i).getJSONObject("values").getString("code"));
                    organization.setName(depArray.getJSONObject(i).getJSONObject("values").getString("name"));
                    organization.setParentId(depArray.getJSONObject(i).getJSONObject("values").getString("parentId"));
                    organization.setStatus(depArray.getJSONObject(i).getJSONObject("values").getString("status"));
                    organizationList.add(organization);
                }
                boolean b = organizationService.saveOrUpdateBatch(organizationList);
                if (b) {
                    log.info("第{}次同步机构", pageIndex);
                }
                if (depArray.size() < pageSize) {
                    break;
                }
                pageIndex++;
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List findUsersByDepId(String depId) {
        try {
            HashMap<String, String> headerParams = new HashMap<>();
            headerParams.put("Content-Type", "application/json");
            String token = NMGYJTIDAASTokenUtils.getToken();
            headerParams.put("Authorization", "bearer " + token);
            List<String> orgIdList = new ArrayList<>();
            orgIdList.add(depId);
            Map bodyParam = new HashMap();
            bodyParam.put("status", new ArrayList<>());

            bodyParam.put("deptId", orgIdList);
            bodyParam.put("identityClassification", "defaultIdentityClassification");
            Map bodyParams = new HashMap();
            bodyParams.put("objectType", "USER");
            bodyParams.put("values", bodyParam);
            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/" +
                    "tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + depId +
                    "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(bodyParams), headerParams);
            IDAASUserResponse object = JSONObject.parseObject(str1, IDAASUserResponse.class);
            List<CsSystemUserCreateBean> users = new ArrayList<>();
            if (null != object && !CollectionUtils.isEmpty(object.getData())) {
                int i = 1;
                for (UserInfo user : object.getData()) {
//                    if (bean.getIsLeader() == user.getValues().getIsLeader()) {
                    CsSystemUserCreateBean userBean = new CsSystemUserCreateBean();
                    userBean.setIsLeader(user.getValues().getIsLeader());
                    userBean.setJob(user.getValues().getJobPosition());
                    userBean.setName(user.getValues().getDisplayName());
                    userBean.setPhone(user.getValues().getUsername());
                    userBean.setOrgName(user.getValues().getOfficeAddress());
                    userBean.setUdOrder(user.getValues().getUdOrder());
                    userBean.setId(user.getId());
                    if (null == userBean.getUdOrder()) {
                        userBean.setUdOrder(i);
                    } else {
                        i = userBean.getUdOrder();
                    }

                    users.add(userBean);
                    i = i + 1;
//                    }
                }
            }
            return users;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public JSONArray findUsersByPhone(String name) {
        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        try {
            headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (JOSEException e) {
            throw new RuntimeException(e);
        }

        Map<String, String> map = new HashMap();
//        map.put("phone_num", "18519275273");
        map.put("keywords", name);
        map.put("object_type", "USER");
        String strUsers = HttpUtils.httpGet(
                "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/search", map, headerParams);
        if (StringUtils.isNotEmpty(strUsers)) {
            JSONObject objUsers = JSON.parseObject(strUsers);
            JSONArray datas = objUsers.getJSONArray("data");
            JSONArray retJSONArray = new JSONArray();
            for (int i = 0; i < datas.size(); i++) {
                JSONObject retJSONObject = new JSONObject();
                JSONObject data = datas.getJSONObject(i);
                JSONObject values = data.getJSONObject("values");
                retJSONObject.put("id", values.get("id"));
                retJSONObject.put("displayName", values.get("displayName"));
                retJSONObject.put("phoneNum", values.get("username"));
                String depLevel = "";
                Map<String, String> mapDept = new HashMap();
                mapDept.put("object_type", "DEPT");
                String parentDeps = HttpUtils.httpGet(
                        "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + values.get("deptId") + "/traces", mapDept, headerParams);
                if (StringUtils.isNotEmpty(parentDeps)) {
                    JSONArray deps = JSON.parseArray(parentDeps);
                    for (int j = 0; j < deps.size(); j++) {
                        JSONObject depObj = deps.getJSONObject(j);
                        JSONObject depValues = depObj.getJSONObject("values");
                        depLevel = ">" + depValues.getString("name") + depLevel;
                    }
                }

                retJSONObject.put("depLevel", depLevel.substring(1, depLevel.length()));
                retJSONArray.add(retJSONObject);
            }
            return retJSONArray;
        }

        return null;
    }

    @Override
    public String upZWWXResources(String phone) {
        String ssoAccessToken=zwwxUtils.getGovWxToken();
        Integer retMap=zwwxUtils.getZWUserInfo(phone,"rescue/rescue-detail?depId=dp-82e68a77deb04025afebba7953aafb61",ssoAccessToken);
        log.info(",,,,,,,,,,,,,,,,,,,,,,,,,,,,政微微信资源同步返回：{}",retMap);
        return zwwxUtils.getGovWxToken();
    }


    public static void main(String[] args) {
        String s = "[\"15114000\",\"\"]";
        List<String> list = JSON.parseArray(s, String.class);
        System.out.println(list);
    }

}
